﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AppFx.TypeExtenders
{
	/// <summary>
	/// A static helper-class providing extended methods dealing with guid's.
	/// </summary>
	public static class GuidExtender
	{
		/// <summary>
		/// Generates an sql-server-friendly, sequential id (last bytes are taken from current datetime)
		/// </summary>
		/// <remarks>
		/// Please remember: This methods increases the risk of creating dupicate guids.
		/// Why is it here:  Sql-Server stores records by the PK (mostly int / guid) - but
		/// if the guid's are very different (last bytes are considered for this) - the sql-server
		/// will use new page for each and every record, which can cause performance-problems.
		/// </remarks>
		/// <returns>A new sequential id.</returns>
		public static Guid GenerateSequential()
		{
			byte[] destinationArray = Guid.NewGuid().ToByteArray();
			DateTime time = new DateTime(0x76c, 1, 1);
			DateTime now = DateTime.Now;
			TimeSpan span = new TimeSpan(now.Ticks - time.Ticks);
			TimeSpan timeOfDay = now.TimeOfDay;
			byte[] bytes = BitConverter.GetBytes(span.Days);
			byte[] array = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
			Array.Reverse(bytes);
			Array.Reverse(array);
			Array.Copy(bytes, bytes.Length - 2, destinationArray, destinationArray.Length - 6, 2);
			Array.Copy(array, array.Length - 4, destinationArray, destinationArray.Length - 4, 4);
			return new Guid(destinationArray);
		}
	}
}
